package com.beigai.imessage.session;

import com.beigai.imessage.server.Mediator;
import com.beigai.imessage.server.SessionMessage;
import com.beigai.imessage.server.UserSession;
import com.beigai.imessage.user.dto.UserFriend;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by xxl on 2017/5/10.
 */
public class MemorySessionCache extends Mediator implements SessionCache {

    private static MemorySessionCache memorySessionCache;

    private MemorySessionCache() {
    }

    public static synchronized MemorySessionCache getInstance() {
        if (memorySessionCache == null)
            memorySessionCache = new MemorySessionCache();
        return memorySessionCache;
    }

    private Map<String, UserSession> sessions = new ConcurrentHashMap<String, UserSession>();

    public UserSession getSession(String code) {
        return sessions.get(code);
    }

    public void addSession(String code, UserSession session) {
        sessions.put(code, session);
    }

    public void removeSession(String code) {
        sessions.remove(code);
    }

    /**
     * 通知中介
     * @param sessionMessage
     * @param userSession
     */
    protected void contact(SessionMessage sessionMessage, UserSession userSession) {
        Map<String, UserFriend> friends = userSession.getFriends();
        Set<String> codes = friends.keySet();
        for (String code : codes) {
            UserSession friendSession = sessions.get(code);
            if (friendSession != null)
                friendSession.getMessage(sessionMessage);
        }

    }
}
